<template>
  <ga-modal
    v-model:visible="visible"
    title-align="start"
    :width="720"
    @close="handleCancel(formRef)"
  >
    <template #title>创建网络(VPC)</template>
    <ga-spin style="width: 100%" :loading="loading">
      <ga-form ref="formRef" :model="formData">
        <ga-form-item
          field="resourceId"
          label="平台名称"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <p class="text_p">{{ type }}</p>
          <!-- <ga-select
            :disabled="menu"
            v-model="formData.resourceId"
            size="small"
            placeholder="请选择平台类型"
            @change="handleChangePlatform"
          >
            <ga-option
              v-for="(item, idx) in platformTypeList"
              :key="idx"
              :label="item.type"
              :value="item.id"
            />
          </ga-select> -->
        </ga-form-item>
        <ga-form-item
          field="name"
          label="网络名称"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-input v-model="formData.name" placeholder="请输入网络名称" />
        </ga-form-item>
        <ga-form-item
          v-if="resourceType !== 'huaweistack'"
          field="vlanId"
          label="Vland ID"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-input v-model="formData.vlanId" placeholder="请输入vlanId" />
        </ga-form-item>
        <ga-form-item
          field="type"
          label="网络类型"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-radio-group
            type="button"
            size="small"
            v-model="formData.type"
            v-for="(item, idx) in networkTypeList"
            :key="idx"
          >
            <ga-radio :value="item.dictValue">{{ item?.dictLabel }}</ga-radio>
          </ga-radio-group>
        </ga-form-item>
        <ga-form-item
          v-if="resourceType === 'vmware' || resourceType === 'smartx'"
          field="cluster"
          label="集群名称"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-select
            v-model="formData.cluster"
            allow-search
            allow-clear
            multiple
            :max-tag-count="2"
            placeholder="选择集群名称"
            @change="handleChangeCluster"
          >
            <ga-option
              v-for="(item, idx) in clusterList"
              :key="idx"
              :label="item?.name"
              :value="item?.uuid"
            />
          </ga-select>
        </ga-form-item>
        <ga-form-item
          field="host"
          v-if="resourceType === 'vmware'"
          label="宿主机"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-select
            v-model="formData.host"
            allow-search
            allow-clear
            multiple
            :max-tag-count="2"
            placeholder="选择宿主机名称"
            @change="handleChangeHost"
          >
            <ga-option
              v-for="(item, idx) in hostList"
              :key="idx"
              :label="item.name"
              :value="item.uuid"
            />
          </ga-select>
        </ga-form-item>
        <ga-form-item
          v-if="resourceType === 'vmware' || resourceType === 'smartx'"
          label="交换机"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
        >
          <ga-card :style="{ backgroundColor: '#F7F9FC' }" :bordered="false">
            <ga-table
              row-key="id"
              :columns="columns"
              :data="tableData"
              :bordered="false"
              size="small"
              :hoverable="false"
              :pagination="false"
              :scroll="{ y: 200 }"
            >
              <template #vdsUuid="{ record }">
                <ga-select
                  v-model="record.vdsUuid"
                  size="small"
                  :default-value="record.vdsUuid"
                >
                  <ga-option
                    v-for="item in record.vds"
                    :key="item.uuid"
                    :value="item.uuid"
                  >
                    {{ item.name }}
                  </ga-option>
                </ga-select>
              </template>
              <template #action="{ rowIndex, record }">
                <ga-link
                  status="danger"
                  :hoverable="false"
                  @click="handleDel(rowIndex, record)"
                >
                  移除
                </ga-link>
              </template>
            </ga-table>
          </ga-card>
        </ga-form-item>
        <ga-form-item
          v-if="resourceType === 'huaweistack' || resourceType === 'easystack'"
          field="physicalNetwork"
          label="物理网络"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-select
            v-if="resourceType === 'huaweistack'"
            v-model="formData.physicalNetwork"
            size="small"
            placeholder="请选择物理网络"
          >
            <ga-option
              v-for="(item, idx) in physicalNetworkList"
              :key="idx"
              :label="item.name"
              :value="item.uuid"
            />
          </ga-select>
          <ga-input
            v-else
            v-model="formData.physicalNetwork"
            placeholder="请输入物理网络"
          />
        </ga-form-item>
        <ga-form-item
          v-if="resourceType === 'easystack'"
          field="isShared"
          label="是否共享"
          label-col-flex="70px"
        >
          <ga-switch size="mini" v-model="formData.isShared" />
        </ga-form-item>
        <ga-form-item
          v-if="resourceType === 'easystack'"
          field="isExternal"
          label="外部网络"
          label-col-flex="70px"
        >
          <ga-switch size="mini" v-model="formData.isExternal" />
        </ga-form-item>
      </ga-form>
    </ga-spin>
    <template #footer>
      <ga-button @click="visible = false">取消</ga-button>
      <ga-button type="primary" @click="handleOk" :loading="okLoading">确定</ga-button>
    </template>
  </ga-modal>
</template>

<script setup>
import { ref, computed, reactive } from "vue";
import { getList } from "@/api/platformMgmt";
import { getExtNetworksList, createNetwork } from "@/api/network";
import { getClusterList } from "@/api/cluserMgmt";
import { byDictToList } from "@/api/dataDictionary.ts";
import { getVdsList } from "@/api/network";
import { Message } from "@garco-design/web-vue";
import { RULE } from "@/constant/validators";
import useLoading from "@/hooks/loading";
import { useRoute } from "vue-router";
import { formatVpcCreateParams } from "@/utils";

const route = useRoute();
const { id } = route.params;
const { resId, menu, uuid, type } = route.query;
const { loading, setLoading } = useLoading(false);
const okLoading = ref(false);
const formRef = ref(null);
const resourceType = ref("vmware");
const platformTypeList = ref([]);
const clusterList = ref([]);
const tableData = ref([]);
const vdsData = ref([]);
const networkTypeList = ref([]);
const physicalNetworkList = ref([]);
const columns = [
  {
    title: "名称",
    dataIndex: "name",
  },
  {
    title: "交换机",
    slotName: "vdsUuid",
    dataIndex: "vdsUuid",
  },
  {
    title: "操作",
    width: 60,
    slotName: "action",
  },
];
const formData = reactive({
  name: "",
  resourceId: "",
  physicalNetwork: "",
  vlanId: "",
  type: "",
  cluster: [],
  host: [],
  isShared: true,
  isExternal: false,
});

// 宿主机列表
const hostList = computed(() => {
  // if (!formData.cluster || formData.cluster.length === 0) {
  //   return vdsData.value;
  // }
  return vdsData.value.filter((item) => {
    return formData.cluster?.includes(item.cluster?.uuid ?? "");
  });
});
// 平台类型方法
const findResourceType = (resourceId) => {
  return platformTypeList.value?.find((item) => item?.id === resourceId)?.type;
};
const visible = ref(false);
const open = async () => {
  visible.value = true;
  setLoading(true);
  await getPlatformList();
};
// 获取物理网络方法
const fetchPhysicalNetworkList = async () => {
  try {
    const { data } = await getExtNetworksList(formData.resourceId, {
      limit: -1,
    });
    physicalNetworkList.value = data || [];
  } catch (error) {
    console.log(error);
  }
};
// 获取networkList方法
const fetchNetworkList = async () => {
  try {
    const { data } = await byDictToList({
      dictType: `${resourceType.value}_network_type`,
      limit: -1,
    });
    networkTypeList.value = data?.items || [];
  } catch (error) {
    console.log(error);
  }
};
const curResId = () => {
  if (menu === "platform") {
    formData.resourceId = Number(id);
  } else if (menu === "cluster" || menu === "host") {
    formData.resourceId = Number(resId);
  } else {
    formData.resourceId = platformTypeList.value?.[0]?.id;
  }
};
// 处理平台名称方法
const getPlatformList = async () => {
  try {
    const { data } = await getList({ limit: -1 });
    platformTypeList.value = data.items;
    curResId();
    handleChangePlatform(formData.resourceId);
  } catch (error) {
    console.log(error);
  }
};
// 选择平台方法 获取vds
const handleChangePlatform = async (val) => {
  reset();
  resourceType.value = findResourceType(Number(val));
  if (resourceType.value === "huaweistack") fetchPhysicalNetworkList();
  formData.physicalNetwork = resourceType.value === "easystack" ? "physnet2" : "";
  fetchNetworkList();
  fetchClusterData();
  try {
    const { data } = await getVdsList(val);
    vdsData.value = data;
    // 集群详情创建
    if (uuid) {
      handleChangeCluster([uuid]);
    }
  } finally {
    setLoading(false);
  }
};
// 获取集群列表方法
const fetchClusterData = async () => {
  try {
    const { data } = await getClusterList({
      limit: -1,
      resourceId: id || formData.resourceId,
    });
    clusterList.value = data?.items || [];
  } catch (error) {}
};
// 选择集群方法
const handleChangeCluster = (val) => {
  formData.host = [];
  hostList.value = [];
  tableData.value = [];
  formData.cluster = val;
  if (resourceType.value !== "vmware") {
    // console.log("val", val);
    tableData.value = vdsData.value.filter((item) => {
      return val?.includes(item.cluster?.uuid ?? "");
    });
  }
};
//选择宿主机方法
const handleChangeHost = () => {
  tableData.value = [];
  tableData.value = vdsData.value.filter((item) => {
    return (
      formData.cluster?.includes(item.cluster?.uuid ?? "") &&
      formData.host?.includes(item?.uuid ?? "")
    );
  });
};
// 处理移除方法
const handleDel = (rowIndex, record) => {
  tableData.value.splice(rowIndex, 1);
  if (resourceType.value === "vmware") {
    formData.host = formData.host.filter((item) => item !== record?.uuid);
  } else {
    formData.cluster = formData.cluster.filter((item) => item !== record?.uuid);
  }
};
// 保存
const emits = defineEmits(["fetchData"]);
const handleOk = async () => {
  const res = await formRef.value?.validate();
  if (!res) {
    okLoading.value = true;
    try {
      const obj = formatVpcCreateParams(resourceType.value, formData, tableData.value);
      const { code } = await createNetwork(obj, "network-vpc");
      if (code === 20000) Message.success("操作成功");
      emits("fetchData");
      visible.value = false;
    } finally {
      okLoading.value = true;
    }
  }
};
const handleCancel = (formEl) => {
  platformTypeList.value = [];
  reset();
  okLoading.value = false;
  formEl.resetFields();
};
const reset = () => {
  formData.cluster = [];
  tableData.value = [];
  vdsData.value = [];
  clusterList.value = [];
};
defineExpose({ open });
</script>

<style lang="scss" scoped>
:deep(.garco-table-header) {
  background-color: #fff !important;
}
</style>
